package com.coszero.utils.encryption

import android.annotation.TargetApi
import android.os.Build
import java.nio.charset.StandardCharsets
import java.security.MessageDigest

/**
 * Desc： MD5加解密操作
 *
 *
 * @author ： xmqian
 * Email:xmqian93@163.com
 * Date: 2019/8/16 15:52
 * @version 1
 */
object MD5Utils {
    /**
     * 小写32位md5加密
     *
     * @param str
     * @return
     */
    @TargetApi(Build.VERSION_CODES.KITKAT)
    fun getMD5(str: String): String {
        var md5: MessageDigest? = null
        try {
            md5 = MessageDigest.getInstance("MD5")
        } catch (e: Exception) {
            e.printStackTrace()
            return ""
        }
        var md5Bytes: ByteArray = ByteArray(0)
        md5Bytes = md5.digest(str.toByteArray(StandardCharsets.UTF_8))
        val hexValue: StringBuffer = StringBuffer()
        for (i in md5Bytes.indices) {
            val `val`: Int = (md5Bytes.get(i).toInt()) and 0xff
            if (`val` < 16) {
                hexValue.append("0")
            }
            hexValue.append(Integer.toHexString(`val`))
        }
        return hexValue.toString()
    }
}
